package ferp.android.views.table.controller;

import android.graphics.Point;
import android.view.View;
import ferp.android.views.CardView;
import ferp.android.views.table.TableView;
import ferp.android.widgets.buttons.TextButton;
import ferp.core.card.Card;
import ferp.core.game.Game;

import java.util.Arrays;

/**
* User: olegs
* Date: 05/01/2015 11:58
*/
public class DropController extends Controller
{
  public DropController(TableView.Listener listener, TableView table, TextButton drop, TextButton without3)
  {
    super(listener, table);

    this.drop = drop;
    this.without3 = without3;

    selected = new CardView[Game.TALON_SIZE];
  }

  @Override
  public void reset()
  {
    Game g = game();

    super.reset();

    // remove selected card views from the array and redraw human's hand
    // do not perform 'deselect' to avoid card flicking when playing with drop/undo drop buttons
    Arrays.fill(selected, null);

    // redraw cards to easily handle pause/resuming activity events
    table.layoutPlayerCards(settings(), g.human().id());
  }

  @Override
  public void onMovingStarted(int player, CardView cv, Point touch)
  {
    if (cv == selected[0])
      deselect(player, cv, 0);
    else
      if (cv == selected[1])
        deselect(player, cv, 1);
      else
        if (selected[0] == null)
          select(player, cv, 0);
        else
          if (selected[1] == null)
            select(player, cv, 1);

    drop.setEnabled(isDropEnabled());
    without3.setEnabled(isWithout3Enabled());
  }

  @Override
  public void onInputButtonClicked(View view, int id)
  {
    super.onInputButtonClicked(view, id);

    // advance and reset current controller in order to move the hidden elevated card views back to the player's hand
    table.advanceController(game(), settings());
  }

  @Override
  public int elevation(int player, CardView cv) {return cv == selected[0] || cv == selected[1] ? -OFFSET : 0;}

  public void select(int player, CardView cv, int i)
  {
    selected[i] = cv;
    select(player, cv);
  }

  public void deselect(int player, CardView cv, int i)
  {
    deselect(player, cv);
    selected[i] = null;
  }

  public boolean isDropEnabled() {return selected[0] != null && selected[1] != null;}
  public boolean isWithout3Enabled() {return selected[0] == null && selected[1] == null;}

  public CardView[] selected() {return selected;}

  @Override
  protected int getMarkIndex(Game g, CardView cv)
  {
    int[] drop = g.scenario().drop();
    Card c = cv.card();

    for (int i = 0; i < drop.length; ++i)
      if (c.hash == drop[i])
        return i;

    return super.getMarkIndex(g, cv);
  }

  private TextButton drop;
  private TextButton without3;
  private CardView[] selected;
}
